package com.ks.listener;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ks.servlet.LoginServlet;

import common.Var;

/**
 * 上下文监听程序，用于初始化访问人数和在线人数，并将访问人数和在线人数保存在上下文环境对象中，使得网站在停止时不丢失访问人数
 * 
 * @author 47475
 *
 */
@WebListener
public class InitNumListener implements ServletContextListener {
	private static Logger log = LoggerFactory.getLogger(LoginServlet.class);

	/** 读取文件获得访问人数 */
	public void contextInitialized(ServletContextEvent sce) {
		ServletContext sc = sce.getServletContext();
		String filename = sc.getRealPath("/WEB-INF/count.txt");
		File file = new File(filename);
		int totalcount = 0;
		if (file.exists()) {
			try (FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr);) {
				totalcount = Integer.parseInt(br.readLine());
				log.debug("===========================InitNumListener初始化，从文件获取总访问人数：【{}】", totalcount);
			} catch (Exception e) {
				log.error("===========================InitNumListener初始化,读取总访问人数文件失败！");
			}
			sc.setAttribute(Var.TOTAL_COUNT, totalcount);
			sc.setAttribute(Var.ACCESS_COUNT, 0);
		}

	}

	/** 把访问人数保存在磁盘文件中 */
	public void contextDestroyed(ServletContextEvent sce) {
		ServletContext sc = sce.getServletContext();
		String filename = sc.getRealPath("/WEB-INF/count.txt");
		File file = new File(filename);
		log.debug("容器销毁，现在总访问人数：{}", sc.getAttribute(Var.TOTAL_COUNT));
		try (FileWriter fr = new FileWriter(file); BufferedWriter br = new BufferedWriter(fr);) {
			br.write(sc.getAttribute(Var.TOTAL_COUNT).toString());
		} catch (IOException e) {
			log.error("保存总访问人数失败！");
		}
		try (FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr);) {
			int totalcount = Integer.parseInt(br.readLine());
			log.debug("【{}】被销毁后保存总访问人数后读取测试人数：{}", this.getClass().getName(), totalcount);
		} catch (Exception e) {
			log.error("测试读取失败！");
		}
	}

}
